package com.heatup.apt.management.controller;

import com.alibaba.fastjson.JSONObject;
import com.heatup.apt.common.constants.DataDictConstants;
import com.heatup.apt.common.util.JsonTools;
import com.heatup.apt.common.util.JsonUtils;
import com.heatup.apt.common.util.OssFileUtil;
import com.heatup.apt.management.service.DataDictService;
import com.heatup.apt.management.service.coach.CoachService;
import com.heatup.apt.management.service.course.CourseService;
import com.heatup.apt.management.service.course.CourseStandardService;
import com.heatup.apt.management.service.store.StoreService;
import com.heatup.apt.management.util.ManageConfigPropertiesUtil;
import com.heatup.apt.model.course.CourseInfo;
import com.heatup.apt.model.course.CourseInfoModel;
import com.heatup.apt.model.course.CourseStandard;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by b3st9u on 16/8/22.
 */
@Controller
@RequestMapping("/system/course")
public class CourseController extends BaseController {
    private final static Logger logger = LoggerFactory.getLogger(CourseController.class);
    @Autowired
    CourseService courseService;
    @Autowired
    CoachService coachService;
    @Autowired
    StoreService storeService;
    @Autowired
    CourseStandardService courseStandardService;
    @Autowired
    DataDictService dataDictService;

    private static final String TEMP_DIR = ManageConfigPropertiesUtil.getString("uploadImagDir").trim();

    /**
     * 檬营列表页
     *
     * @return
     */
    @RequestMapping(value = "/to_course_camp_list", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toCourseCamp() {
        ModelAndView modelAndView = new ModelAndView("course/course-camp-list");
        modelAndView.addObject("coachList", coachService.queryAllCoachInfo());
        modelAndView.addObject("storeList", storeService.queryAllOnlineStore());
        return modelAndView;
    }


    /**
     * 檬营列表分页查询
     *
     * @param response
     * @return
     */
    @RequestMapping(value = "/course_camp_list", method = {RequestMethod.GET, RequestMethod.POST})
    public void courseCampList(HttpServletResponse response,
                               @RequestParam int pageIndex,
                               @RequestParam int pageSize,
                               @RequestParam(required = false) Integer id,
                               @RequestParam(required = false) Integer coachId,
                               @RequestParam(required = false) Integer storeId,
                               @RequestParam(required = false) Integer status) {

        if (pageIndex > 0)
            --pageIndex;
        if (pageSize <= 0)
            pageSize = 10;
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("pageIndex", pageIndex);
        paramsMap.put("pageSize", pageSize);
        paramsMap.put("id", id);
        paramsMap.put("coachId", coachId);
        paramsMap.put("storeId", storeId);
        paramsMap.put("status", status);

        Map<String, Object> map = courseService.queryCourseList(paramsMap);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("courseList", map.get("courseList"));
        jsonObject.put("courseCount", map.get("courseCount"));
        responseSendMsg(response, JsonUtils.toJsonStrWithDateFormat(jsonObject));
    }


    /**
     * 檬营添加页面
     *
     * @return
     */
    @RequestMapping(value = "/to_course_camp_add", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView addCourse() {
        ModelAndView modelAndView = new ModelAndView("course/course-camp-add");
        modelAndView.addObject("coachList", coachService.queryAllCoachInfo());
        modelAndView.addObject("storeList", storeService.queryAllOnlineStore());
        modelAndView.addObject("dataDictList", JsonUtils.obj2Json(dataDictService.queryDataDicts(DataDictConstants.DICT_TYPE_COURSE_ATTR)));
        modelAndView.addObject("courseStandards", courseStandardService.queryAllCourseStandard());
        return modelAndView;
    }

    /**
     * 檬营编辑页面
     *
     * @return
     */
    @RequestMapping(value = "/to_course_camp_edit", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView editCourse(@RequestParam Integer id) {
        ModelAndView modelAndView = new ModelAndView("course/course-camp-edit");
        modelAndView.addObject("coachList", coachService.queryAllCoachInfo());
        modelAndView.addObject("storeList", storeService.queryAllOnlineStore());
        modelAndView.addObject("courseStandards", courseStandardService.queryAllCourseStandard());
        modelAndView.addObject("dataDictList", JsonUtils.obj2Json(dataDictService.queryDataDicts(DataDictConstants.DICT_TYPE_COURSE_ATTR)));
        CourseInfoModel c = courseService.queryCourseById(id);
        modelAndView.addObject("course", c);
        modelAndView.addObject("courseJson", JsonUtils.obj2Json(c));
        return modelAndView;
    }

    /**
     * 自动读取标准课程
     *
     * @param id
     */
    @RequestMapping(value = "/course_standard", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String queryStand(@RequestParam int id) {
        CourseStandard courseStandard = courseStandardService.queryCourseStandardWithResourceById(id);
        return JsonTools.jsonSer(courseStandard);
    }

    /**
     * 檬营保存
     *
     * @return
     */
    @RequestMapping(value = "/course_camp_save", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String saveCourse(CourseInfoModel courseInfo) {
        if (courseInfo == null) {
            return "false";
        }

        if (courseInfo.getId() != null) {
            courseInfo.setUpdatedBy(getUserInfo().getId());
            int i = courseService.queryCourseOrderByCourseId(courseInfo.getId());
            if (i > 0) {
                CourseInfoModel courseInfoOld = courseService.queryCourseById(courseInfo.getId());
                if (
//                        courseInfo.getStartTime().compareTo(courseInfoOld.getStartTime()) != 0 || //目前需求可以修改上课时间
//                         courseInfo.getEndTime().compareTo(courseInfoOld.getEndTime()) != 0 ||
                        courseInfo.getServicePrice().getPrimePrice().compareTo(courseInfoOld.getServicePrice().getPrimePrice()) != 0
                        || courseInfo.getServicePrice().getPrice().compareTo(courseInfoOld.getServicePrice().getPrice()) !=0
                        ) {
                    return "当前已有订单用户,课程价格无法修改";
                }
                /**
                 * 1. 如果当前报名人数 >= 课程最大人数， 则只能增，加能减
                 * 2. 如果 课程最大人数有变化，则触发排队的订单是否要变成正常订单
                 */
                if(courseInfoOld.getMaxCount().intValue() <= courseInfoOld.getCurrentCount().intValue()){
                    //如果修改的课程最大人数小于之前的最大数
                    if(courseInfo.getMaxCount().intValue() < courseInfoOld.getMaxCount().intValue()){
                        return "该檬营当前人数已报满，只能增加课程的最大人数值。";
                    }
                }else{
                    if ((courseInfoOld.getMaxCount().intValue() - courseInfo.getMaxCount() .intValue())
                            >
                            (courseInfoOld.getMaxCount().intValue() - courseInfoOld.getCurrentCount().intValue())) {
                        return "该檬营已有订单关联，过度减少最大人数会导致出现排队异常。";
                    }
                }
            }
        } else {
            courseInfo.setCreatedBy(getUserInfo().getId());
        }

        if (courseService.saveCourse(courseInfo)) {
            return "success";
        }
        return "false";
    }

    /**
     * 檬营下架
     */
    @RequestMapping(value = "/course_close", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String courseClose(CourseInfo courseInfo) {
        String result = "";
        if (courseInfo == null) {
            result = "下架失败";
            return result;
        }
        boolean success = courseService.closeCourseById(courseInfo.getId());
        if (success) {
            result = "下架成功";
        }
        return result;
    }

    /**
     * 檬营删除
     */
    @RequestMapping(value = "/course_delete", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String courseDelete(CourseInfo courseInfo) {
        String result = "";
        if (courseInfo == null) {
            result = "删除失败";
            return result;
        }
        boolean success = courseService.delCourseInfoById(courseInfo.getId());
        if (success) {
            result = "删除成功";
        }
        return result;
    }


    /**
     * 图片上传
     *
     * @param image
     * @param response
     */
    @RequestMapping(value = "/upload_pic", method = {RequestMethod.GET, RequestMethod.POST})
    public void upload(@RequestParam("file") MultipartFile image, HttpServletResponse response) throws IOException {
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        try {
            if (!image.isEmpty()) {
                jsonObject.put("error", false);
                File tempDir = new File(TEMP_DIR);
                if (!tempDir.exists()) {
                    if (!tempDir.isDirectory()) {
                        boolean ret = tempDir.mkdir();
                    }
                }
                File file = new File(TEMP_DIR + image.getOriginalFilename());
                image.transferTo(file);
                String fileExt = image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf("."));
                String imagePath = OssFileUtil.uploadFile(file.getPath(),
                        UUID.randomUUID().toString().substring(0, 8) + fileExt);
                jsonObject.put("url", imagePath);
                responseSendMsg(response, jsonObject.toJSONString());
            } else {
                jsonObject.put("error", true);
                jsonObject.put("url", "");
                responseSendMsg(response, jsonObject.toJSONString());
            }
        } catch (Exception ex) {
            logger.error("CourseController upload method error! " + ex.getMessage() + ex.toString());
        }
    }

//    /**
//     * 删除图片
//     * @param fileName
//     */
//    @RequestMapping(value = "/delete_pic")
//    @ResponseBody
//    public String deleteImg(@RequestParam String fileName){
//
//        OssFileUtil.deleteFile(fileName);
//
//        return fileName;
//    }
}
